"use strict";
import Basic from './basic'
import Vue from "vue"

class Upload extends Basic {
    constructor (...args) {
        super(...args);
        this.fileUploadUrl = this.$config.fileUploadUrl
        this.secretFileUploadUrl = this.$config.secretFileUploadUrl
    }

    /**
     * 单视频上传
     * @param fileType
     * @param max
     * @param onProgressUpdate
     * @param api
     * @param compressed
     * @param maxDuration
     * @param camera
     * @returns {Promise<unknown>}
     */
    singleVideo (fileType, max = 10 * 1024 * 1024, onProgressUpdate, api = '', {compressed = false, maxDuration = 60, camera = "back"} = {}) {
        const vm = this;
        const fileUploadUrl = api || this.fileUploadUrl;
        const timer = setTimeout(vm.hideLoading, 3000);
        return new Promise((resolve, reject) => {
            uni.chooseVideo({
                //从相册选择
                sourceType: ['album', 'camera'],
                compressed,
                maxDuration,
                camera,
                success: async function (res) {
                    clearTimeout(timer);
                    const tempFilePath = res.tempFilePath;
                    const data = {
                        errMsg: res.errMsg,
                        url: tempFilePath
                    };
                    if (res.size > max) return resolve({
                        code: 0,
                        message: `文件上传过大，请选择不超过${vm.bytes2Size(max)}大小的文件`,
                        fileInfo: res
                    });
                    const result = await vm.uploadFile({
                        url: fileUploadUrl,
                        filePath: data.url,
                        name: 'file',
                        formData: {fileType},
                        header: {},
                        onProgressUpdate ({progress} = {}) {
                            console.log(`上传进度${progress}%`);
                            if (typeof onProgressUpdate === "function") {
                                onProgressUpdate(...arguments)
                            } else {
                                Vue.$loading.show(`上传进度${progress}%`)
                                if (progress >= 100) Vue.$loading.hide()
                            }
                        }
                    });
                    if (result.code === 0) {
                        resolve({...result, videoInfo: res})
                    } else {
                        resolve(result);
                    }
                },
                fail (err) {
                    resolve({code: -1, message: '上传失败', err})
                }
            });
        })
    }

    /**
     * 单图上传
     *
     * @param fileType 文件类型
     * @param onProgressUpdate 监听上传进度
     * @param api 选填 上传接口（不填默认普通文件）
     * @returns {Promise<unknown>}
     */
    singleImage (fileType, onProgressUpdate, api = '') {
        const vm = this;
        const fileUploadUrl = api || this.fileUploadUrl;
        const timer = setTimeout(vm.hideLoading, 3000);
        return new Promise((resolve, reject) => {
            uni.chooseImage({
                count: 1, //默认9
                //可以指定是原图还是压缩图，默认二者都有
                sizeType: ['original', 'compressed'],
                //从相册选择
                sourceType: ['album', 'camera'],
                success: async function (res) {
                    clearTimeout(timer);
                    const tempFilePaths = res.tempFilePaths;
                    const data = {
                        errMsg: res.errMsg,
                        url: tempFilePaths[0]
                    };
                    const result = await vm.uploadFile({
                        url: fileUploadUrl,
                        filePath: data.url,
                        name: 'file',
                        formData: {
                            fileType
                        },
                        header: {},
                        onProgressUpdate ({progress} = {}) {
                            console.log(`上传进度${progress}%`);
                            if (typeof onProgressUpdate === "function") {
                                onProgressUpdate(...arguments)
                            } else {
                                Vue.$loading.show(`上传进度${progress}%`)
                                if (progress >= 100) Vue.$loading.hide()
                            }
                        }
                    });
                    if (result.code === 0) {
                        const info = await vm.getImageInfoSync(data.url);
                        resolve({
                            ...result,
                            imageInfo: info
                        })
                    } else {
                        resolve(result);
                    }
                },
                fail (err) {
                    resolve({
                        code: -1,
                        message: '上传失败',
                        err
                    })
                }
            });
        })
    }

    /**
     * 单文件上传
     *
     * @param fileType 文件类型
     * @param type 文件格式类型
     * @param extension 文件筛选
     * @param max 最大上传大小
     * @param onProgressUpdate 监听上传进度
     * @param api 选填 上传接口（不填默认普通文件）
     * @returns {Promise<unknown>}
     */
    singleFiles (fileType, {type = "all", extension, max = 30 * 1024 * 1024, onProgressUpdate} = {}, api = '') {
        const vm = this;
        const fileUploadUrl = this.fileUploadUrl;
        const timer = setTimeout(vm.hideLoading, 3000);
        return new Promise((resolve, reject) => {
            let suffixs = null;
            //#ifdef MP-WEIXIN
            if (type === "pdf") {
                type = "file";
                suffixs = "pdf"
            }
            return wx.chooseMessageFile({
                count: 1, //默认9
                type,
                extension,
                success: async function (res) {
                    clearTimeout(timer);
                    if (res.tempFiles.length === 0) return resolve({
                        code: 0,
                        message: '取消上传'
                    });
                    const tempFile = res.tempFiles[0];
                    if (tempFile.size > max) return resolve({
                        code: 0,
                        message: `文件上传过大，请选择不超过${vm.bytes2Size(max)}大小的文件`,
                        fileInfo: tempFile
                    });

                    const name = tempFile.name.split('.');
                    const Suffix = name[name.length - 1];

                    if (typeof suffixs === "string" && Suffix !== suffixs) {
                        return resolve({
                            code: -1,
                            message: `请选择上传${suffixs}格式文件`,
                            fileInfo: tempFile
                        })
                    }

                    const data = {
                        errMsg: res.errMsg,
                        url: tempFile.path
                    };
                    const result = await vm.uploadFile({
                        url: fileUploadUrl,
                        filePath: data.url,
                        name: 'file',
                        formData: {
                            fileType,
                            docName: tempFile.name
                        },
                        header: {},
                        onProgressUpdate ({progress} = {}) {
                            console.log(`上传进度${progress}%`);
                            if (typeof onProgressUpdate === "function") {
                                onProgressUpdate(...arguments)
                            } else {
                                Vue.$loading.show(`上传进度${progress}%`)
                                if (progress >= 100) Vue.$loading.hide()
                            }
                        }
                    });
                    if (result.code === 0) {
                        resolve({
                            ...result,
                            fileInfo: tempFile
                        })
                    } else {
                        resolve(result);
                    }
                },
                fail (err) {
                    resolve({
                        code: -1,
                        message: '上传失败',
                        err
                    })
                }
            });
            //#endif
            reject()
        })
    }

    /**
     * 私密单图上传
     *
     * @param type 上传类型（选填）（不填为普通上传类型，bizLicense：营业执照类型）
     * @param onProgressUpdate 监听上传进度
     * @param fileType 文件类型
     * @returns {Promise<unknown>}
     */
    secretImageUpdate (type = "", onProgressUpdate, fileType) {
        let secretFileUploadUrl = this.secretFileUploadUrl;
        if (type) secretFileUploadUrl = `${secretFileUploadUrl}/${type}`;
        return this.singleImage(fileType, onProgressUpdate, secretFileUploadUrl);
    }


}

export default new Upload();
